package com.thti.mecool.client.activity;

import java.io.File;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.command.send.system.GetSend;
import com.thti.mecool.client.command.send.user.UserSend;
import com.thti.mecool.client.protocol.system.VersionDetailProtocol;
import com.thti.mecool.client.util.RegexPattern;
import com.thti.mecool.client.util.StringUtil;
import com.thti.mecool.client.util.Util;

public class LoginActivity extends BaseActivity {
	public static Handler handler;
	private ImageButton login_button;
	private String userName;
	private String passWord;
	private EditText mecool_login_username;
	private EditText mecool_login_password;
	private boolean autoLogin = false;
	SharedPreferences load_LoginInfo;
	SharedPreferences save_LoginInfo;
	SharedPreferences update_Info;
	ProgressDialog LoginProgress;
	CheckBox box;
	TelephonyManager tm;
	private boolean isCheck;
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (!LoginProgress.isShowing()) {
				setCurrentMesg(null);
			} else {
				if (getCurrentUser() == null) {
					if (getCurrentMesg() == null) {
						handler.postDelayed(runnable, 1000);
					} else {
						Toast.makeText(LoginActivity.this,
								getCurrentMesg().getContent(), 4000).show();
						handler.post(runnable);
						LoginProgress.dismiss();
						setCurrentMesg(null);
						autoLogin = false;
						handler.removeCallbacks(runnable);
					}
				} else {
					if (isCheck) {
						save_LoginInfo = getSharedPreferences(
								"LoginPreferences", 0);
						Editor save_editor = save_LoginInfo.edit();
						save_editor.putString("userName", mecool_login_username
								.getText().toString());
						save_editor.putString("passWord", "");
						save_editor.putBoolean("autoLogin", isCheck);
						save_editor.commit();
					} else {
						save_LoginInfo = getSharedPreferences(
								"LoginPreferences", 0);
						Editor save_editor = save_LoginInfo.edit();
						save_editor.remove("userName").remove("passWord");
						save_editor.putString("userName", "");
						save_editor.putString("passWord", "");
						save_editor.putString("userId", "");
						save_editor.putBoolean("autoLogin", isCheck);
						save_editor.commit();
					}
					save_LoginInfo = getSharedPreferences("LocationService", 0);
					Editor save = save_LoginInfo.edit();
					save.putString("userName", getCurrentUser().getLoginName());
					save.commit();
					if (LoginProgress.isShowing()) {
						LoginProgress.dismiss();
					}
					handler.removeCallbacks(runnable);
					Intent i = new Intent();
					i.setClass(LoginActivity.this,
							HomeActivity.class);
					startActivity(i);
					finish();
				}
			}
		} 
	};
//	Handler handler = new Handler() {
//		@Override
//		public void handleMessage(Message msg) {
//			super.handleMessage(msg);
//			switch (msg.what) {
//			case HandlerConstant.GETLOGIN:
//				LoginProgress = new ProgressDialog(LoginActivity.this);
//				LoginProgress.setTitle("明酷督导管理系统");
//				LoginProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//				LoginProgress.setMessage("正在登陆……");
//				LoginProgress.show();
//				TelephonyManager tm = (TelephonyManager)getSystemService("phone"); 
//				Util.print("IMEI: "+tm.getDeviceId());
//				UserSend.userLogin(mecool_login_username.getText().toString(),
//						mecool_login_password.getText().toString(),tm.getDeviceId());
//				handler.post(runnable);
//				break;
//
//			case HandlerConstant.GETAUTOLOGIN:
//				userName = load_LoginInfo.getString("userName", "null");
//				passWord = load_LoginInfo.getString("passWord", "null");
//				box.setChecked(true);
//				if (!userName.equals("null") && !passWord.equals("null")) {
//					mecool_login_username.setText(userName);
//					mecool_login_password.setText(passWord);
//				}
//				// handler.sendEmptyMessage(HandlerConstant.GETLOGIN);
//				break;
//			}
//		}
//	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.noTitle();
		setContentView(R.layout.mecool_login);
		Cache.add(this);
		Cache.setmContext(this);
		Editor save=getSharedPreferences("Setting", 0).edit();
		String[] names=new String[]{"BootLoad","AutoRefresh"};
		save.putBoolean(names[0], true);
		save.putBoolean(names[1], true);
		save.commit();
		box = (CheckBox) findViewById(R.id.mecool_autoLogin);
		box.setOnCheckedChangeListener(listener);
		mecool_login_username = (EditText) findViewById(R.id.mecool_login_username);
		mecool_login_password = (EditText) findViewById(R.id.mecool_login_password);
		tm = (TelephonyManager)getSystemService("phone"); 
		handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					switch (msg.what) {
					case HandlerConstant.GETLOGIN:
						LoginProgress = new ProgressDialog(LoginActivity.this);
						LoginProgress.setTitle("明酷督导管理系统");
						LoginProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
						LoginProgress.setMessage("正在登陆……");
						LoginProgress.show();
						tm = (TelephonyManager)getSystemService("phone"); 
						Util.print("IMEI: "+tm.getDeviceId());
						UserSend.userLogin(mecool_login_username.getText().toString(),
								mecool_login_password.getText().toString(),tm.getDeviceId());
						handler.post(runnable);
						break;

					case HandlerConstant.GETAUTOLOGIN:
						userName = load_LoginInfo.getString("userName", "null");
						passWord = load_LoginInfo.getString("passWord", "null");
						box.setChecked(true);
						if (!userName.equals("null") && !passWord.equals("null")) {
							mecool_login_username.setText(userName);
							mecool_login_password.setText(passWord);
						}
						// handler.sendEmptyMessage(HandlerConstant.GETLOGIN);
						break;
					case 0xDD:
						VersionDetailProtocol apklatest=(VersionDetailProtocol)msg.obj;
						if(!StringUtil.isBlank(apklatest.getOptUrl()))
						showUpdataDialog(apklatest.getOptUrl(),apklatest.getVersion());
//						showUpdataDialog("http://192.168.2.241:8080/MecoolSuperviseClient.apk",apklatest.getVersion());
						break;
					}
				}
			};
	    GetSend.getVersion(tm.getDeviceId(), getResources().getString(R.string.app_version_id));
		
		load_LoginInfo = getSharedPreferences("LoginPreferences", 0);
		autoLogin = load_LoginInfo.getBoolean("autoLogin", false);
		if (autoLogin) {
			handler.sendEmptyMessage(HandlerConstant.GETAUTOLOGIN);
		}
		login_button = (ImageButton) findViewById(R.id.mecool_login_button);
		login_button.setOnClickListener(login_button_listener);
		/**
		 * 测试用
		 */
		// User user=new User7416
		update_Info=getSharedPreferences("UpdatePreferences", 0);
		if(!StringUtil.isBlank(update_Info.getString("path", null))){
			File fileApk=new File(update_Info.getString("path", null));
			if(fileApk.exists()){
				fileApk.delete();
			}
			Editor update_editor = update_Info.edit();
			update_editor.putString("path", null);
			update_editor.commit();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		BaseActivity.setCurrentUser(null);
		BaseActivity.setCurrentMesg(null);
	}

	OnCheckedChangeListener listener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			isCheck = isChecked;
			System.out.println("isCheck      :      " + isCheck);
		}
	};
	private OnClickListener login_button_listener = new ImageButton.OnClickListener() {
		@Override
		public void onClick(View v) {
			if(StringUtil.isBlank(mecool_login_username.getText().toString())){
				mecool_login_username.setError("用户名不能为空");
				return;
			}
			if (RegexPattern.isChars(mecool_login_username.getText().toString())) {
				mecool_login_username.setError("请误输入非法字符");
				return;
			}
			if(StringUtil.isBlank(mecool_login_password.getText().toString())){
				mecool_login_username.setError("密码不能为空");
				return;
			}
//			if (RegexPattern.isPassWord(mecool_login_username.getText().toString())) {
//				mecool_login_username.setError("请误输入非法字符");
//				return;
//			}
			handler.sendEmptyMessage(HandlerConstant.GETLOGIN);
		}
	};
	
	
	
	protected void showUpdataDialog(final String url,final String infohorizon) {  
	    	Intent intent=new Intent();
	    	intent.setClass(LoginActivity.this,UpdateActivity.class);
			intent.putExtra("updateUrl",url);
			intent.putExtra("info", infohorizon);
			startActivity(intent);
	 
	    
	}
}
